from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.edge.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.edge.service import Service
import random
import time

# -------------------------- 配置参数（根据你的环境修改）--------------------------
EDGE_BINARY_PATH = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
EDGE_DRIVER_PATH = r"G:\python实战\driver\msedgedriver.exe"
INITIAL_MANUAL_OPERATE_TIME = 60 # 首次手动操作时间（秒）
COMMENT_COUNT_PER_VIDEO = 2 # 每个视频发送的评论数量
MIN_WAIT_TIME = 1 # 每条评论最小间隔（秒）
MAX_WAIT_TIME = 5 # 每条评论最大间隔（秒）
VERIFY_CODE_SLEEP_TIME = 30 # 验证码处理休眠时间（秒）
SWITCH_VIDEO_SLEEP_TIME = 20 # 切换视频的休眠时间（秒）
# --------------------------------------------------------------------------------

edge_options = Options()
edge_options.binary_location = EDGE_BINARY_PATH

try:
    edge_service = Service(executable_path=EDGE_DRIVER_PATH)
    driver = webdriver.Edge(service=edge_service, options=edge_options)
    driver.maximize_window()
    wait = WebDriverWait(driver, 15)
    print("✅ Edge浏览器启动成功！")
except Exception as e:
    print(f"❌ EdgeDriver初始化失败：{e}")
    exit()


def get_current_uploader_name():
    """获取当前视频的上传者（博主）名称（从评论区作者卡片获取）"""
    try:
        # 使用 CSS Selector 定位到评论区的作者名称容器
        uploader_name = driver.execute_script("""
            var authorCard = document.querySelector('div.author-card-user-name');
            return authorCard ? authorCard.innerText.trim() : '';
        """)

        if uploader_name:
            return uploader_name

        print("⚠️  主方法获取博主名称失败，尝试备用 XPath 方案...")
        # 备用方案：使用 XPath 定位
        uploader_element = wait.until(
            EC.presence_of_element_located((By.XPATH, "//div[contains(@class, 'author-card-user-name')]"))
        )
        uploader_name = uploader_element.text.strip()
        return uploader_name

    except Exception as e:
        print(f"⚠️  无法获取当前视频的博主名称: {e}")
        return "未知博主"


try:
    driver.get("https://www.douyin.com/")
    print("🌐 已打开抖音网页版，请手动登录（若未登录）...")
    time.sleep(5)

    print(f"\n⌛ 请在 {INITIAL_MANUAL_OPERATE_TIME} 秒内完成以下操作：")
    print("1. 找到你想评论的第一个视频并点击进入")
    print("2. 点开视频下方的「评论」按钮（确保评论输入框可见）")
    for i in range(INITIAL_MANUAL_OPERATE_TIME, 0, -1):
        print(f"倒计时：{i}秒", end="\r")
        time.sleep(1)
    print("\n✅ 手动操作时间结束，开始自动评论...")

    batch_number = 1
    while True:
        uploader_name = get_current_uploader_name()
        print(f"\n==================================================")
        print(f"📢 开始为第 {batch_number} 个视频发送评论...")
        print(f"👤 目标博主: {uploader_name}")
        print(f"==================================================")

        batch_successful = False

        for comment_idx in range(COMMENT_COUNT_PER_VIDEO):
            random_num = random.randint(1, 100)
            comment_content = str(random_num)

            try:
                comment_input_div = wait.until(
                    EC.presence_of_element_located((By.CSS_SELECTOR, "div.public-DraftStyleDefault-block"))
                )

                comment_input_div.click()
                time.sleep(random.uniform(0.2, 0.5))

                comment_input_div.send_keys(comment_content)
                print(f"📝 为 {uploader_name} 输入第 {comment_idx + 1} 条评论：'{comment_content}'")
                time.sleep(random.uniform(0.3, 0.7))

                comment_input_div.send_keys(Keys.ENTER)
                print(f"✅ 为 {uploader_name} 发送第 {comment_idx + 1} 条评论成功！")
                batch_successful = True

                wait_time = random.uniform(MIN_WAIT_TIME, MAX_WAIT_TIME)
                time.sleep(wait_time)

            except Exception as e:
                print(f"\n❌ 为 {uploader_name} 发送第 {comment_idx + 1} 条评论失败：{e}")
                print(f"⚠️  可能触发验证码或评论区已关闭！将休眠 {VERIFY_CODE_SLEEP_TIME} 秒，请处理！")

                for i in range(VERIFY_CODE_SLEEP_TIME, 0, -1):
                    print(f"⏳ 处理倒计时：{i}秒", end="\r")
                    time.sleep(1)

                print("\n✅ 休眠结束，尝试继续发送当前批次...")
                uploader_name = get_current_uploader_name()  # 重新获取博主名，以防页面变化
                continue

        if batch_successful:
            print(f"\n🎉 为博主 {uploader_name} 的 {COMMENT_COUNT_PER_VIDEO} 条评论发送完成！")
            batch_number += 1

        print(f"\n⌛ 即将休眠 {SWITCH_VIDEO_SLEEP_TIME} 秒，请在此期间手动切换到下一个视频并打开评论区！")
        print("操作完成后无需任何操作，脚本将自动继续。")
        print("若要停止脚本，请在控制台按下 Ctrl + C。")
        for i in range(SWITCH_VIDEO_SLEEP_TIME, 0, -1):
            print(f"⏳ 切换视频倒计时：{i}秒", end="\r")
            time.sleep(1)
        print("\n✅ 休眠结束，准备为下一个视频发送评论...")

except KeyboardInterrupt:
    print("\n\n🛑 用户手动停止了脚本。")
except Exception as e:
    print(f"\n\n❌ 脚本执行发生未知异常：{e}")
finally:
    driver.quit()
    print("🔒 浏览器已关闭！")